package com.hundsun.cprs.yyt.service.quota.service.impl;

import com.hundsun.cprs.yyt.common.base.BaseService;
import com.hundsun.cprs.yyt.common.exception.ServiceCodeException;
import com.hundsun.cprs.yyt.service.account.domain.Account;
import com.hundsun.cprs.yyt.service.account.enums.EnumQuotaTransType;
import com.hundsun.cprs.yyt.service.account.service.AccountService;
import com.hundsun.cprs.yyt.service.common.Constants;
import com.hundsun.cprs.yyt.service.quota.dao.QuotaDao;
import com.hundsun.cprs.yyt.service.quota.dao.QuotaImportLogDao;
import com.hundsun.cprs.yyt.service.quota.domain.Quota;
import com.hundsun.cprs.yyt.service.quota.domain.QuotaImportLog;
import com.hundsun.cprs.yyt.service.quota.domain.query.QuotaImportLogQuery;
import com.hundsun.cprs.yyt.service.quota.service.QuotaHoldService;
import com.hundsun.cprs.yyt.service.quota.service.QuotaImportLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;

/**
 * @author herong22384
 * @date 2019/9/1 10:45
 */
@Service
public class QuotaImportLogServiceImpl extends BaseService implements QuotaImportLogService {

    public static final String YYT_BATCH_IMPORT_LOCK = Constants.YYT_BATCH_IMPORT_LOCK;

    @Autowired
    private QuotaImportLogDao quotaImportLogDao;
    @Autowired
    @Qualifier("commonThreadPool")
    private Executor executor;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AccountService accountService;
    @Autowired
    private QuotaDao quotaDao;
    @Autowired
    private QuotaHoldService quotaHoldService;

    @Override
    public void queryByPage(QuotaImportLogQuery query) {
        List<QuotaImportLog> quotaImportLogs = quotaImportLogDao.queryByPage(query);
        query.compatible(quotaImportLogs);
    }

    @Override
    public void batchInsert(List<QuotaImportLog> datas) {
        quotaImportLogDao.batchInsert(datas);
    }

    @Override
    public void handleBatchImport() {
        //异步处理导入记录
        executor.execute(new Runnable() {
            public void run() {
                try{
                    while (true){
                        QuotaImportLogQuery query = new QuotaImportLogQuery();
                        query.setStatus(0);
                        query.setPageNo(1);
                        query.setPageSize(200);
                        query.setOrderRule("ASC");
                        queryByPage(query);

                        if (query.getTotalCount() == 0){
                            break;
                        }

                        //更新该批数据状态为处理中
                        quotaImportLogDao.updateStatusByBatch(query.getData(), 1,"处理中");

                        //处理批量审核导入
                        doBatchImport(query.getData());
                    }
                }finally {
                    //释放redis锁
                    redisTemplate.delete(YYT_BATCH_IMPORT_LOCK);
                }
            }
        });
    }

    protected void doBatchImport(List<QuotaImportLog> datas){
        List<QuotaImportLog> logs = new ArrayList<>();
        for (QuotaImportLog log : datas){
            try{
                //1.校验用户是否正常
                Account user = accountService.getAccountByFundAccountFromCache(log.getFundAccount());
                if (user == null){
                    log.setStatus(-1);
                    log.setRemark("会员信息不存在");
                    quotaImportLogDao.updateByPrimaryKeySelective(log);
                    continue;
                }
                //2.校验配额是否存在
                Quota quota = quotaDao.getQuotaByName(log.getQuotaName());
                if (quota == null){
                    log.setStatus(-1);
                    log.setRemark("配额类型不存在");
                    quotaImportLogDao.updateByPrimaryKeySelective(log);
                    continue;
                }
                //3.校验配额是否存在
                if (log.getQuotaAmount()<=0L){
                    log.setStatus(-1);
                    log.setRemark("配额数量必须大于0");
                    quotaImportLogDao.updateByPrimaryKeySelective(log);
                    continue;
                }
                //4.增加配额持仓
                quotaHoldService.addQuota(user.getUserId(),quota.getId(),log.getQuotaAmount(),EnumQuotaTransType.TRANS_0202.getCode(),"批量导入");
                log.setStatus(2);
                log.setRemark("成功导入");
                logs.add(log);
            }catch (ServiceCodeException e){
                logger.error(e);
                log.setStatus(-1);
                log.setRemark(e.getErrorDesc());
                quotaImportLogDao.updateByPrimaryKeySelective(log);
            }catch (Exception e){
                logger.error(e);
                log.setStatus(-1);
                log.setRemark("数据错误");
                quotaImportLogDao.updateByPrimaryKeySelective(log);
            }
        }
        if (!CollectionUtils.isEmpty(logs)){
            //批量更新审核记录
            quotaImportLogDao.batchUpdate(logs);
        }
    }
}
